// pages/stats/stats.js
const app = getApp()
const { WxCharts } = require('../../utils/wxcharts')

// 添加日期格式化辅助函数
function formatDateForIOS(dateStr) {
  if (!dateStr) return null;
  // 如果已经是ISO格式或者包含T，直接返回
  if (dateStr.includes('T')) return dateStr;
  // 如果包含空格，将空格替换为T
  if (dateStr.includes(' ')) return dateStr.replace(' ', 'T');
  // 如果只有日期，直接返回
  if (dateStr.length <= 10) return dateStr;
  return dateStr;
}

// 修改日期解析相关代码
function parseDateSafely(dateStr) {
  if (!dateStr) return null;
  try {
    // 尝试直接解析
    const date = new Date(dateStr);
    if (!isNaN(date.getTime())) return date;
    
    // 如果解析失败，尝试格式化后再解析
    const formattedDate = formatDateForIOS(dateStr);
    return new Date(formattedDate);
  } catch (e) {
    // 静默处理日期解析错误
    return null;
  }
}

Page({
  data: {
    timeRange: 'today', // 默认显示今日
    startDate: '',
    endDate: '',
    healthScore: 0,
    healthStatus: '良好',
    healthStatusColor: '#2196F3', // 默认颜色
    continuousDays: 0,
    recordCount: 0, // 添加记录次数
    avgDuration: 0, // 添加平均时长
    lastTime: '', // 添加最近时间
    showRules: false, // 控制规则弹窗显示
    timeStats: [], // 时间规律统计
    reportButtonText: '点击我生成今日报告', // 添加新的数据属性
    healthAdvice: [
      {
        id: 1,
        name: '水果',
        emoji: 'https://gitee.com/teajoy/image/raw/master/images/水果.jpeg',
        color: '#10b981',
        title: '多吃纤维素',
        description: '增加蔬菜、水果和全谷物的摄入，有助于保持肠道健康。'
      },
      {
        id: 2,
        name: '喝水',
        emoji: 'https://gitee.com/teajoy/image/raw/master/images/喝水.jpg',
        color: '#60a5fa',
        title: '多喝水',
        description: '每天喝足够的水，有助于软化大便，预防便秘。'
      },
      {
        id: 3,
        name: '运动',
        emoji: 'https://gitee.com/teajoy/image/raw/master/images/运动.gif',
        color: '#f59e0b',
        title: '适量运动',
        description: '规律的体育锻炼可以促进肠道蠕动，改善消化功能。'
      },
      {
        id: 4,
        name: '排便',
        emoji: 'https://gitee.com/teajoy/image/raw/master/images/排便.jpeg',
        color: '#8b5cf6',
        title: '规律排便',
        description: '养成定时排便的习惯，有助于肠道健康。'
      }
    ],
    todayStats: {
      count: 0,
      lastTime: '暂无',
      mainType: {
        name: '暂无',
        color: '#cccccc'
      },
      avgScore: 0,
      avgDuration: 0
    },
    timeGroups: [],
    showReportPreview: false, // 是否显示报告预览
    reportTitle: '', // 报告标题
    showLoading: false, // 添加 loading 状态
  },

  onLoad() {
    this.initDateRange();
    this.loadStats();
    this.loadTodayStats();
    this.checkRecords();  // 添加检查
  },

  // 添加onShow生命周期函数，确保每次显示页面时都更新数据
  onShow() {
    // 从本地存储同步最新数据到全局
    const localRecords = wx.getStorageSync('poopRecords') || [];
    app.globalData.records = localRecords;
    
    // 重新加载统计数据
    this.initDateRange();
    this.loadStats();
    this.loadTodayStats();
  },

  // 初始化日期范围
  initDateRange() {
    const now = new Date()
    let startDate = new Date()
    let endDate = new Date()
    
    switch (this.data.timeRange) {
      case 'today':
        // 今日范围就是当天的开始到结束
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
        endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)
        break
      case 'week':
        const day = now.getDay() || 7
        startDate.setDate(now.getDate() - day + 1)
        endDate.setDate(startDate.getDate() + 6)
        break
      case 'month':
        startDate.setDate(1)
        endDate.setMonth(now.getMonth() + 1, 0)
        break
      case 'year':
        startDate.setMonth(0, 1)
        endDate.setMonth(11, 31)
        break
    }
    
    this.setData({
      startDate: this.formatDate(startDate),
      endDate: this.formatDate(endDate)
    })
  },

  // 设置时间范围
  setTimeRange(e) {
    const range = e.currentTarget.dataset.range
    let buttonText = '点击我生成报告'
    
    // 根据时间范围设置按钮文本
    switch (range) {
      case 'today':
        buttonText = '点击我生成今日报告'
        break
      case 'week':
        buttonText = '点击我生成本周报告'
        break
      case 'month':
        buttonText = '点击我生成本月报告'
        break
      case 'year':
        buttonText = '点击我生成年度报告'
        break
    }
    
    this.setData({ 
      timeRange: range,
      reportButtonText: buttonText
    })
    
    // 重新初始化日期范围
    this.initDateRange()
    
    // 重新加载所有数据
    this.loadStats()
    this.loadTodayStats()
  },

  // 加载统计数据
  loadStats() {
    const records = this.getFilteredRecords()
    this.calculateHealthScore(records)
    this.calculateContinuousDays(records)
    this.calculateTimeStats(records)
    this.calculateRecordStats(records) // 添加记录统计计算
  },

  getFilteredRecords() {
    // 确保 records 存在，优先从本地存储加载
    if (!app.globalData.records || !Array.isArray(app.globalData.records)) {
      const localRecords = wx.getStorageSync('poopRecords') || [];
      app.globalData.records = localRecords;
    }
    
    if (app.globalData.records.length === 0) {
      return [];
    }
    
    const startTime = new Date(this.data.startDate).getTime();
    const endTime = new Date(this.data.endDate).getTime() + 24 * 60 * 60 * 1000 - 1;

    return app.globalData.records.filter(record => {
      // 数据验证
      if (!record || !record.date || !record.time) {
        console.warn('发现无效记录:', record);
        return false;
      }

      try {
        // 使用新的日期解析函数
        const recordDateTime = parseDateSafely(`${record.date}T${record.time}`);
        if (!recordDateTime || isNaN(recordDateTime.getTime())) {
          console.warn('日期解析失败:', record.date, record.time);
          return false;
        }
        
        const recordTime = recordDateTime.getTime();
        return recordTime >= startTime && recordTime <= endTime;
      } catch (error) {
        console.warn('记录过滤出错:', error, record);
        return false;
      }
    });
  },

  // 计算健康评分和状态
  calculateHealthScore(records) {
    if (records.length === 0) {
      this.setData({
        healthScore: 0,
        healthStatus: '暂无数据',
        healthStatusColor: '#999999'
      })
      return 0
    }

    // 计算正常排便的比例
    const normalCount = records.filter(r => {
      // 检查 typeId 或 typeName，支持多种数据格式
      return r.typeId === '1' || r.typeId === 1 || 
             r.typeName === '正常' || r.type === '正常';
    }).length;

    const score = Math.round((normalCount / records.length) * 100);

    // 根据分数确定状态和颜色
    let status = '良好'
    let color = '#2196F3'

    if (score >= 90) {
      status = '优秀'
      color = '#4CAF50'
    } else if (score >= 70) {
      status = '良好'
      color = '#2196F3'
    } else if (score >= 50) {
      status = '一般'
      color = '#FFC107'
    } else {
      status = '需注意'
      color = '#FF5722'
    }

    this.setData({
      healthScore: score,
      healthStatus: status,
      healthStatusColor: color
    })
    return score
  },

  // 计算连续记录天数
  calculateContinuousDays(records) {
    if (records.length === 0) {
      this.setData({ continuousDays: 0 })
      return 0
    }
    
    const sortedRecords = records.sort((a, b) => {
      const dateA = parseDateSafely(`${a.date}T${a.time}`)
      const dateB = parseDateSafely(`${b.date}T${b.time}`)
      return dateB - dateA
    })

    let continuousDays = 1
    let lastDate = parseDateSafely(`${sortedRecords[0].date}T${sortedRecords[0].time}`)
    
    for (let i = 1; i < sortedRecords.length; i++) {
      const currentDate = parseDateSafely(`${sortedRecords[i].date}T${sortedRecords[i].time}`)
      const dayDiff = Math.round((lastDate - currentDate) / (24 * 60 * 60 * 1000))
      
      if (dayDiff === 1) {
        continuousDays++
        lastDate = currentDate
      } else {
        break
      }
    }
    
    this.setData({ continuousDays })
    return continuousDays
  },

  // 统计时间规律
  calculateTimeStats(records) {
    // 初始化时间段分组
    const timeGroups = [
      { name: '凌晨', count: 0, hours: '0:00-5:59' }, // 0:00-5:59
      { name: '早上', count: 0, hours: '6:00-11:59' }, // 6:00-11:59
      { name: '中午', count: 0, hours: '12:00-13:59' }, // 12:00-13:59
      { name: '下午', count: 0, hours: '14:00-17:59' }, // 14:00-17:59
      { name: '晚上', count: 0, hours: '18:00-23:59' }  // 18:00-23:59
    ]

    // 统计每个时间段的记录数
    records.forEach(record => {
      if (!record.time) return; // 防止时间为空的情况
      
      const time = record.time
      const hour = parseInt(time.split(':')[0])

      // 添加更严格的时间验证
      if (isNaN(hour) || hour < 0 || hour > 23) return;

      if (hour >= 0 && hour < 6) {
        timeGroups[0].count++
      } else if (hour >= 6 && hour < 12) {
        timeGroups[1].count++
      } else if (hour >= 12 && hour < 14) {
        timeGroups[2].count++
      } else if (hour >= 14 && hour < 18) {
        timeGroups[3].count++
      } else {
        timeGroups[4].count++
      }
    })

    // 计算最大计数值
    const maxCount = Math.max(...timeGroups.map(group => group.count))
    
    // 根据最大值计算合适的刻度
    const yAxisTicks = this.calculateYAxisTicks(maxCount)

    // 添加统计摘要
    const totalRecords = records.length
    const mostActiveTime = timeGroups.reduce((max, group) => 
      group.count > max.count ? group : max, timeGroups[0])

    this.setData({
      timeGroups,
      noTimeData: records.length === 0,
      maxCount: maxCount || 1, // 避免除以0
      yAxisTicks,
      totalRecords,
      mostActiveTime: mostActiveTime.count > 0 ? mostActiveTime : null
    })
  },

  // 计算Y轴刻度
  calculateYAxisTicks(maxValue) {
    if (maxValue === 0) {
      return [0]
    }

    // 计算合适的刻度间隔
    const idealTickCount = 5 // 理想的刻度数量
    let interval = Math.ceil(maxValue / (idealTickCount - 1))
    
    // 将间隔调整为更易读的数字（如5、10、20等）
    const magnitude = Math.pow(10, Math.floor(Math.log10(interval)))
    const normalizedInterval = interval / magnitude
    
    if (normalizedInterval <= 1) interval = magnitude
    else if (normalizedInterval <= 2) interval = 2 * magnitude
    else if (normalizedInterval <= 5) interval = 5 * magnitude
    else interval = 10 * magnitude

    // 生成刻度数组
    const ticks = []
    const maxTick = Math.ceil(maxValue / interval) * interval
    for (let i = maxTick; i >= 0; i -= interval) {
      ticks.push(i)
    }

    return ticks
  },

  // 绘制时间规律图表
  drawTimeChart(timeStats) {
 
    
    // 检查是否有数据
    const hasData = timeStats && timeStats.some(val => val > 0);

    
    if (!hasData) {
      // 如果没有数据，显示空状态
      this.setData({
        noTimeData: true
      });
      return;
    }
    
    this.setData({
      noTimeData: false
    });
    
    try {
      // 简化时间数据，按照早上、中午、下午、晚上、凌晨分组
      const timeGroups = [
        { name: '凌晨', hours: [0, 1, 2, 3, 4, 5], count: 0 },
        { name: '早上', hours: [6, 7, 8, 9, 10, 11], count: 0 },
        { name: '中午', hours: [12, 13], count: 0 },
        { name: '下午', hours: [14, 15, 16, 17], count: 0 },
        { name: '晚上', hours: [18, 19, 20, 21, 22, 23], count: 0 }
      ];
      
      // 统计每个时间段的排便次数
      timeStats.forEach((count, hour) => {
        for (const group of timeGroups) {
          if (group.hours.includes(hour)) {
            group.count += count;
            break;
          }
        }
      });
      

      
      // 将timeGroups数据保存到页面状态中，用于显示数字统计
      this.setData({
        timeGroups: timeGroups.map(group => ({
          name: group.name,
          count: group.count
        }))
      });
      
    } catch (error) {
      this.setData({
        noTimeData: true
      });
    }
  },
  
  // 为每个时间段分配颜色 - 保留此函数以备将来使用
  getColorForTimePeriod(name) {
    const colorMap = {
      '凌晨': '#8b5cf6', // 紫色
      '早上': '#60a5fa', // 蓝色
      '中午': '#f59e0b', // 橙色
      '下午': '#10b981', // 绿色
      '晚上': '#ec4899'  // 粉色
    };
    
    return colorMap[name] || '#999999'; // 默认灰色
  },

  // 格式化日期：YYYY-MM-DD
  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  loadTodayStats: function() {
    // 确保 records 存在
    if (!app.globalData.records) {
      app.globalData.records = [];
      this.setData({
        todayStats: {
          count: 0,
          lastTime: '暂无',
          mainType: {
            name: '暂无',
            color: '#cccccc'
          },
          avgScore: 0,
          avgDuration: 0
        }
      });
      return;
    }
    
    // 获取今天的日期（年-月-日格式）
    const today = new Date();
    const todayStr = this.formatDate(today);
    
    // 从全局数据中筛选出今天的记录
    const todayRecords = app.globalData.records.filter(record => {
      return record.date === todayStr;
    });
    
    if (todayRecords.length === 0) {
      // 如果今天没有记录
      this.setData({
        todayStats: {
          count: 0,
          lastTime: '暂无',
          mainType: {
            name: '暂无',
            color: '#cccccc'
          },
          avgScore: 0,
          avgDuration: 0
        }
      });
      return;
    }
    
    // 计算今日排便次数
    const count = todayRecords.length;
    
    // 获取最近一次排便时间
    const sortedRecords = [...todayRecords].sort((a, b) => {
      const dateA = parseDateSafely(`${a.date}T${a.time}`);
      const dateB = parseDateSafely(`${b.date}T${b.time}`);
      return dateB - dateA;  // 降序排序，最新的在前
    });
    const lastRecord = sortedRecords[0];
    const lastTime = lastRecord.time;
    
    // 计算平均时长
    const totalDuration = todayRecords.reduce((sum, record) => sum + (record.duration || 0), 0);
    const avgDuration = Math.round(totalDuration / count);
    
    // 统计各类型次数
    const typeCounts = {};
    todayRecords.forEach(record => {
      if (record.type) {
        typeCounts[record.type] = (typeCounts[record.type] || 0) + 1;
      }
    });
    
    // 找出出现最多的类型
    let mainType = {
      name: '暂无',
      color: '#cccccc'
    };
    
    let maxCount = 0;
    Object.entries(typeCounts).forEach(([type, count]) => {
      if (count > maxCount) {
        maxCount = count;
        const typeInfo = app.globalData.poopTypes.find(t => t.id === parseInt(type));
        if (typeInfo) {
          mainType = {
            name: typeInfo.name,
            color: typeInfo.color
          };
        }
      }
    });
    
    // 计算平均分数
    const totalScore = todayRecords.reduce((sum, record) => {
      return sum + (record.score || 0);
    }, 0);
    const avgScore = Math.round(totalScore / count);
    
    // 更新统计数据
    this.setData({
      todayStats: {
        count,
        lastTime,
        mainType,
        avgScore,
        avgDuration
      }
    });
  },

  // 显示健康规则弹窗
  showHealthRules() {
    this.setData({
      showRules: true
    });
  },

  // 隐藏健康规则弹窗
  hideHealthRules() {
    this.setData({
      showRules: false
    });
  },

  // 阻止冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 计算记录统计
  calculateRecordStats(records) {
    if (!records || records.length === 0) {
      this.setData({
        recordCount: 0,
        avgDuration: 0,
        lastTime: '暂无'
      })
      return
    }

    // 计算记录次数
    const recordCount = records.length

    // 计算平均时长
    const totalDuration = records.reduce((sum, record) => {
      return sum + (record.duration || 0)
    }, 0)
    const avgDuration = Math.round(totalDuration / recordCount)

    // 获取最近一次记录时间
    const sortedRecords = [...records].sort((a, b) => {
      const dateA = parseDateSafely(`${a.date}T${a.time}`)
      const dateB = parseDateSafely(`${b.date}T${b.time}`)
      return dateB - dateA
    })
    const lastTime = sortedRecords[0].time

    this.setData({
      recordCount,
      avgDuration,
      lastTime
    })
  },

  // 生成报告
  generateReport() {
    // 数据处理
    // 根据当前timeRange确定报告类型
    const reportTypeMap = {
      'today': 'daily',
      'week': 'weekly',
      'month': 'monthly',
      'year': 'yearly'
    }
    
    const reportType = reportTypeMap[this.data.timeRange]
    const reportTitle = this.getReportTitle()

    // 直接跳转到报告页面
    wx.navigateTo({
      url: `/packageA/pages/report/report?type=${reportType}&title=${reportTitle}`
    })
  },

  // 获取报告标题
  getReportTitle() {
    const titleMap = {
      'today': '今日健康报告',
      'week': '本周健康报告',
      'month': '本月健康报告',
      'year': '年度健康报告'
    }
    return titleMap[this.data.timeRange]
  },

  // 绘制报告
  async drawReport(ctx, type) {
    const { width, height } = ctx.canvas

    // 清空画布
    ctx.clearRect(0, 0, width, height)

    // 设置背景色
    ctx.fillStyle = '#f0fdf4' // 更浅的绿色背景
    ctx.fillRect(0, 0, width, height)
    // 处理类型数据
    // 根据类型绘制不同的统计图表
    switch(type) {
      case 'daily':
        await this.drawDailyReport(ctx)
        break
      case 'weekly':
        await this.drawWeeklyReport(ctx)
        break
      case 'monthly':
        await this.drawMonthlyReport(ctx)
        break
      case 'yearly':
        await this.drawYearlyReport(ctx)
        break
    }
  },

  // 绘制日报
  async drawDailyReport(ctx) {
    const { width, height } = ctx.canvas
    const padding = width * 0.05 // 使用相对padding
    
    // 绘制背景
    const gradient = ctx.createLinearGradient(0, 0, 0, height)
    gradient.addColorStop(0, '#a7f3d0')  // 浅绿色
    gradient.addColorStop(1, '#d1fae5')  // 更浅的绿色
    ctx.fillStyle = gradient
    ctx.fillRect(0, 0, width, height)

    // 绘制白色卡片背景
    const cardPadding = padding
    const radius = 20
    ctx.fillStyle = 'rgba(255, 255, 255, 0.95)'
    ctx.beginPath()
    // 左上角
    ctx.moveTo(cardPadding + radius, cardPadding)
    // 右上角
    ctx.lineTo(width - cardPadding - radius, cardPadding)
    ctx.arcTo(width - cardPadding, cardPadding, width - cardPadding, cardPadding + radius, radius)
    // 右下角
    ctx.lineTo(width - cardPadding, height - cardPadding - radius)
    ctx.arcTo(width - cardPadding, height - cardPadding, width - cardPadding - radius, height - cardPadding, radius)
    // 左下角
    ctx.lineTo(cardPadding + radius, height - cardPadding)
    ctx.arcTo(cardPadding, height - cardPadding, cardPadding, height - cardPadding - radius, radius)
    // 左上角
    ctx.lineTo(cardPadding, cardPadding + radius)
    ctx.arcTo(cardPadding, cardPadding, cardPadding + radius, cardPadding, radius)
    ctx.closePath()
    ctx.fill()

    // 绘制标题
    ctx.fillStyle = '#059669'  // 深绿色
    ctx.font = `bold ${Math.floor(width * 0.06)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText(this.data.reportTitle, width / 2, padding * 2.5)

    // 获取今日数据
    const today = new Date()
    const todayStr = this.formatDate(today)
    const todayRecords = (app.globalData.records || []).filter(record => record.date === todayStr)

    // 绘制主要统计数据
    const centerY = height * 0.25
    ctx.fillStyle = '#059669'
    ctx.font = `bold ${Math.floor(width * 0.12)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText(`${todayRecords.length}次`, width / 2, centerY)
    
    ctx.font = `${Math.floor(width * 0.045)}px sans-serif`
    ctx.fillStyle = '#047857'
    ctx.fillText('今日，你一共拉了', width / 2, centerY - 30)

    if (todayRecords.length > 0) {
      // 计算平均分数（添加默认值0）
      const avgScore = Math.round(todayRecords.reduce((sum, record) => sum + (record.score || 0), 0) / todayRecords.length)
      
      // 绘制平均分
      ctx.font = `bold ${Math.floor(width * 0.08)}px sans-serif`
      ctx.fillStyle = '#059669'
      ctx.fillText(`${avgScore}分`, width / 2, centerY + 60)
      ctx.font = `${Math.floor(width * 0.045)}px sans-serif`
      ctx.fillStyle = '#047857'
      ctx.fillText('平均便便得分', width / 2, centerY + 90)

      // 计算超过的用户百分比（这里使用虚拟数据）
      const percentage = 89.9
      ctx.fillStyle = '#059669'
      ctx.font = `${Math.floor(width * 0.045)}px sans-serif`
      ctx.fillText(`超过${percentage}%的便便星人`, width / 2, centerY + 130)

      // 绘制时间分布折线图
      const chartArea = {
        x: padding * 2,
        y: height * 0.5,
        width: width - padding * 4,
        height: height * 0.3
      }

      // 绘制横轴标签和折线图
      const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      ctx.font = '12px sans-serif'
      ctx.fillStyle = '#6b7280'
      ctx.textAlign = 'center'
      weekdays.forEach((day, index) => {
        const x = chartArea.x + (index * (chartArea.width / 6))
        ctx.fillText(day, x, chartArea.y + chartArea.height + 20)
      })

      // 绘制折线
      ctx.beginPath()
      ctx.strokeStyle = '#059669'
      ctx.lineWidth = 2
      todayRecords.forEach((record, index) => {
        const score = record.score || 0 // 添加默认值
        const x = chartArea.x + (index * (chartArea.width / 6))
        const y = chartArea.y + chartArea.height - (score * 30)
        if (index === 0) {
          ctx.moveTo(x, y)
        } else {
          ctx.lineTo(x, y)
        }
      })
      ctx.stroke()

      // 绘制数据点
      todayRecords.forEach((record, index) => {
        const score = record.score || 0 // 添加默认值
        const x = chartArea.x + (index * (chartArea.width / 6))
        const y = chartArea.y + chartArea.height - (score * 30)
        
        // 绘制白色背景圆
        ctx.beginPath()
        ctx.fillStyle = 'white'
        ctx.arc(x, y, 4, 0, Math.PI * 2)
        ctx.fill()
        
        // 绘制绿色边框
        ctx.beginPath()
        ctx.strokeStyle = '#059669'
        ctx.lineWidth = 2
        ctx.arc(x, y, 4, 0, Math.PI * 2)
        ctx.stroke()
        
        // 绘制数值（添加默认值处理）
        ctx.fillStyle = '#059669'
        ctx.font = '12px sans-serif'
        ctx.textAlign = 'center'
        ctx.fillText(score.toString(), x, y - 15)
      })

      // 绘制底部提示文字
      ctx.fillStyle = '#047857'
      ctx.font = `${Math.floor(width * 0.04)}px sans-serif`
      ctx.textAlign = 'center'
      ctx.fillText('每个微小的记录，都是为更好的排便提供指引~', width / 2, height - padding * 2)
    } else {
      // 如果没有记录
      ctx.fillStyle = '#6b7280'
      ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
      ctx.textAlign = 'center'
      ctx.fillText('今日暂无记录', width / 2, height / 2)
    }
  },

  // 绘制周报
  async drawWeeklyReport(ctx) {
    const { width, height } = ctx.canvas
    const padding = 20
    const chartArea = {
      x: padding,
      y: 60,
      width: width - padding * 2,
      height: height - 100
    }

    // 获取本周数据
    const today = new Date()
    const weekStart = new Date(today)
    weekStart.setDate(today.getDate() - today.getDay())
    weekStart.setHours(0, 0, 0, 0)
    
    const weekRecords = this.data.records.filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= weekStart
    })


    // 绘制基本信息
    ctx.fillStyle = '#1f2937'
    ctx.font = '14px sans-serif'
    ctx.textAlign = 'left'
    
    const y = chartArea.y
    ctx.fillText(`本周记录：${weekRecords.length} 次`, padding, y)
    
    if (weekRecords.length > 0) {
      // 计算平均时长
      const totalDuration = weekRecords.reduce((sum, record) => sum + record.duration, 0)
      const avgDuration = Math.round(totalDuration / weekRecords.length)
      ctx.fillText(`平均时长：${avgDuration} 分钟`, padding, y + 25)

      // 按天统计数据
      const dayDistribution = new Array(7).fill(0)
      const dayDurations = new Array(7).fill(0)
      weekRecords.forEach(record => {
        const recordDate = new Date(record.date)
        const dayIndex = recordDate.getDay()
        dayDistribution[dayIndex]++
        dayDurations[dayIndex] += record.duration
      })

      // 找出最大值用于缩放
      const maxCount = Math.max(...dayDistribution)
      const barWidth = chartArea.width / 7
      const barMaxHeight = chartArea.height - 100

      // 绘制坐标轴
      ctx.beginPath()
      ctx.strokeStyle = '#e5e7eb'
      ctx.moveTo(chartArea.x, y + 60)
      ctx.lineTo(chartArea.x + chartArea.width, y + 60)
      ctx.stroke()

      // 绘制星期标签
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      ctx.font = '12px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillStyle = '#6b7280'
      weekdays.forEach((day, index) => {
        const x = chartArea.x + index * barWidth + barWidth / 2
        ctx.fillText(day, x, y + 80)
      })

      // 绘制柱状图
      dayDistribution.forEach((count, day) => {
        const x = chartArea.x + day * barWidth
        const barHeight = count > 0 ? (count / maxCount) * barMaxHeight : 0
        
        // 绘制柱子
        ctx.fillStyle = '#60a5fa'
        ctx.fillRect(
          x + 4,
          y + 60 - barHeight,
          barWidth - 8,
          barHeight
        )

        if (count > 0) {
          // 显示次数
          ctx.fillStyle = '#1f2937'
          ctx.font = '12px sans-serif'
          ctx.textAlign = 'center'
          ctx.fillText(
            `${count}次`,
            x + barWidth / 2,
            y + 55 - barHeight
          )

          // 显示平均时长
          const avgDuration = Math.round(dayDurations[day] / count)
          ctx.fillText(
            `${avgDuration}分钟`,
            x + barWidth / 2,
            y + 40 - barHeight
          )
        }
      })

      // 绘制总结
      ctx.fillStyle = '#1f2937'
      ctx.font = '14px sans-serif'
      ctx.textAlign = 'left'
      const summary = this.generateWeeklySummary(dayDistribution, dayDurations)
      ctx.fillText(summary, padding, height - padding)
    } else {
      // 如果没有记录
      ctx.fillStyle = '#6b7280'
      ctx.font = '14px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillText('本周暂无记录', width / 2, height / 2)
    }
  },

  // 生成周报总结文字
  generateWeeklySummary(dayDistribution, dayDurations) {
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    
    // 找出最活跃的日子
    let maxCount = 0
    let activeDays = []
    dayDistribution.forEach((count, day) => {
      if (count > maxCount) {
        maxCount = count
        activeDays = [day]
      } else if (count === maxCount && maxCount > 0) {
        activeDays.push(day)
      }
    })

    if (maxCount === 0) {
      return '本周暂无规律'
    }

    // 找出平均时长最长的日子
    let maxDuration = 0
    let longestDays = []
    dayDurations.forEach((duration, day) => {
      if (dayDistribution[day] === 0) return
      const avgDuration = duration / dayDistribution[day]
      if (avgDuration > maxDuration) {
        maxDuration = avgDuration
        longestDays = [day]
      } else if (avgDuration === maxDuration) {
        longestDays.push(day)
      }
    })

    const activeDayStrings = activeDays.map(day => weekdays[day])
    const longestDayStrings = longestDays.map(day => weekdays[day])
    
    return `最活跃：${activeDayStrings.join('、')} | 时长最长：${longestDayStrings.join('、')}`
  },

  // 绘制月报
  async drawMonthlyReport(ctx) {
    const { width, height } = ctx.canvas
    const padding = 20
    const chartArea = {
      x: padding,
      y: 60,
      width: width - padding * 2,
      height: height - 100
    }

    // 获取本月数据
    const today = new Date()
    const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)
    const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0)
    const daysInMonth = monthEnd.getDate()
    
    const monthRecords = this.data.records.filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= monthStart && recordDate <= monthEnd
    })

    // 绘制基本信息
    ctx.fillStyle = '#1f2937'
    ctx.font = '14px sans-serif'
    ctx.textAlign = 'left'
    
    const y = chartArea.y
    ctx.fillText(`本月记录：${monthRecords.length} 次`, padding, y)
    
    if (monthRecords.length > 0) {
      // 计算平均时长
      const totalDuration = monthRecords.reduce((sum, record) => sum + record.duration, 0)
      const avgDuration = Math.round(totalDuration / monthRecords.length)
      ctx.fillText(`平均时长：${avgDuration} 分钟`, padding, y + 25)

      // 按日期统计数据
      const dateDistribution = new Array(daysInMonth).fill(0)
      const dateDurations = new Array(daysInMonth).fill(0)
      monthRecords.forEach(record => {
        const recordDate = new Date(record.date)
        const dateIndex = recordDate.getDate() - 1
        dateDistribution[dateIndex]++
        dateDurations[dateIndex] += record.duration
      })

      // 找出最大值用于缩放
      const maxCount = Math.max(...dateDistribution)
      const barWidth = Math.min(20, chartArea.width / daysInMonth)
      const barMaxHeight = chartArea.height - 100

      // 绘制坐标轴
      ctx.beginPath()
      ctx.strokeStyle = '#e5e7eb'
      ctx.moveTo(chartArea.x, y + 60)
      ctx.lineTo(chartArea.x + daysInMonth * barWidth, y + 60)
      ctx.stroke()

      // 绘制日期标签
      ctx.font = '12px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillStyle = '#6b7280'
      for (let i = 0; i < daysInMonth; i += 5) {
        const x = chartArea.x + i * barWidth + barWidth / 2
        ctx.fillText(`${i + 1}日`, x, y + 80)
      }

      // 绘制柱状图
      dateDistribution.forEach((count, date) => {
        const x = chartArea.x + date * barWidth
        const barHeight = count > 0 ? (count / maxCount) * barMaxHeight : 0
        
        // 绘制柱子
        ctx.fillStyle = count > 0 ? '#60a5fa' : '#e5e7eb'
        ctx.fillRect(
          x + 2,
          y + 60 - (barHeight || 2),
          barWidth - 4,
          barHeight || 2
        )

        if (count > 0) {
          // 显示次数（当柱子足够宽时）
          if (barWidth >= 15) {
            ctx.fillStyle = '#1f2937'
            ctx.font = '10px sans-serif'
            ctx.textAlign = 'center'
            ctx.fillText(
              count.toString(),
              x + barWidth / 2,
              y + 55 - barHeight
            )
          }
        }
      })

      // 绘制总结
      ctx.fillStyle = '#1f2937'
      ctx.font = '14px sans-serif'
      ctx.textAlign = 'left'
      const summary = this.generateMonthlySummary(dateDistribution, dateDurations)
      ctx.fillText(summary, padding, height - padding)

      // 绘制图例
      const legendY = height - padding - 40
      ctx.fillStyle = '#60a5fa'
      ctx.fillRect(padding, legendY, 16, 16)
      ctx.fillStyle = '#1f2937'
      ctx.textAlign = 'left'
      ctx.fillText('有记录', padding + 24, legendY + 12)

      ctx.fillStyle = '#e5e7eb'
      ctx.fillRect(padding + 100, legendY, 16, 16)
      ctx.fillStyle = '#1f2937'
      ctx.fillText('无记录', padding + 124, legendY + 12)
    } else {
      // 如果没有记录
      ctx.fillStyle = '#6b7280'
      ctx.font = '14px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillText('本月暂无记录', width / 2, height / 2)
    }
  },

  // 生成月报总结文字
  generateMonthlySummary(dateDistribution, dateDurations) {
    // 计算记录天数
    const recordDays = dateDistribution.filter(count => count > 0).length
    
    // 找出最活跃的日期
    let maxCount = 0
    let activeDates = []
    dateDistribution.forEach((count, date) => {
      if (count > maxCount) {
        maxCount = count
        activeDates = [date + 1]
      } else if (count === maxCount && maxCount > 0) {
        activeDates.push(date + 1)
      }
    })

    if (maxCount === 0) {
      return '本月暂无规律'
    }

    // 找出连续记录的最长天数
    let currentStreak = 0
    let maxStreak = 0
    dateDistribution.forEach((count) => {
      if (count > 0) {
        currentStreak++
        maxStreak = Math.max(maxStreak, currentStreak)
      } else {
        currentStreak = 0
      }
    })

    const activeDateStrings = activeDates.map(date => `${date}日`)
    return `记录天数：${recordDays}天 | 最长连续：${maxStreak}天 | 最活跃：${activeDateStrings.join('、')}`
  },

  // 绘制年报
  async drawYearlyReport(ctx) {
    const { width, height } = ctx.canvas
    const padding = 20
    const chartArea = {
      x: padding,
      y: 60,
      width: width - padding * 2,
      height: height - 100
    }

    // 获取今年数据
    const today = new Date()
    const yearStart = new Date(today.getFullYear(), 0, 1)
    const yearEnd = new Date(today.getFullYear(), 11, 31, 23, 59, 59)
    
    const yearRecords = this.data.records.filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= yearStart && recordDate <= yearEnd
    })

    // 绘制基本信息
    ctx.fillStyle = '#1f2937'
    ctx.font = '14px sans-serif'
    ctx.textAlign = 'left'
    
    const y = chartArea.y
    ctx.fillText(`今年记录：${yearRecords.length} 次`, padding, y)
    
    if (yearRecords.length > 0) {
      // 计算平均时长
      const totalDuration = yearRecords.reduce((sum, record) => sum + record.duration, 0)
      const avgDuration = Math.round(totalDuration / yearRecords.length)
      ctx.fillText(`平均时长：${avgDuration} 分钟`, padding, y + 25)

      // 按月份统计数据
      const monthDistribution = new Array(12).fill(0)
      const monthDurations = new Array(12).fill(0)
      const monthDays = new Array(12).fill(0) // 记录天数
      const monthRecordDates = Array.from({ length: 12 }, () => new Set()) // 每月记录的日期集合
      
      yearRecords.forEach(record => {
        const recordDate = new Date(record.date)
        const monthIndex = recordDate.getMonth()
        monthDistribution[monthIndex]++
        monthDurations[monthIndex] += record.duration
        monthRecordDates[monthIndex].add(recordDate.getDate())
      })

      // 计算每月记录天数
      monthRecordDates.forEach((dates, index) => {
        monthDays[index] = dates.size
      })

      // 找出最大值用于缩放
      const maxCount = Math.max(...monthDistribution)
      const barWidth = chartArea.width / 12
      const barMaxHeight = chartArea.height - 100

      // 绘制坐标轴
      ctx.beginPath()
      ctx.strokeStyle = '#e5e7eb'
      ctx.moveTo(chartArea.x, y + 60)
      ctx.lineTo(chartArea.x + chartArea.width, y + 60)
      ctx.stroke()

      // 绘制月份标签
      const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      ctx.font = '12px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillStyle = '#6b7280'
      months.forEach((month, index) => {
        const x = chartArea.x + index * barWidth + barWidth / 2
        ctx.fillText(month, x, y + 80)
      })

      // 绘制柱状图
      monthDistribution.forEach((count, month) => {
        const x = chartArea.x + month * barWidth
        const barHeight = count > 0 ? (count / maxCount) * barMaxHeight : 0
        
        // 绘制柱子
        ctx.fillStyle = '#60a5fa'
        ctx.fillRect(
          x + 4,
          y + 60 - barHeight,
          barWidth - 8,
          barHeight
        )

        if (count > 0) {
          // 显示次数和天数
          ctx.fillStyle = '#1f2937'
          ctx.font = '12px sans-serif'
          ctx.textAlign = 'center'
          ctx.fillText(
            `${count}次`,
            x + barWidth / 2,
            y + 55 - barHeight
          )
          ctx.fillText(
            `${monthDays[month]}天`,
            x + barWidth / 2,
            y + 40 - barHeight
          )
        }
      })

      // 绘制总结
      ctx.fillStyle = '#1f2937'
      ctx.font = '14px sans-serif'
      ctx.textAlign = 'left'
      const summary = this.generateYearlySummary(monthDistribution, monthDays)
      ctx.fillText(summary, padding, height - padding)

      // 绘制图例
      const legendY = height - padding - 40
      ctx.fillStyle = '#1f2937'
      ctx.textAlign = 'left'
      ctx.fillText('柱高：记录次数 | 数字：记录次数/天数', padding, legendY + 12)
    } else {
      // 如果没有记录
      ctx.fillStyle = '#6b7280'
      ctx.font = '14px sans-serif'
      ctx.textAlign = 'center'
      ctx.fillText('今年暂无记录', width / 2, height / 2)
    }
  },

  // 生成年报总结文字
  generateYearlySummary(monthDistribution, monthDays) {
    // 计算记录天数
    const totalDays = monthDays.reduce((sum, days) => sum + days, 0)
    
    // 找出最活跃的月份
    let maxCount = 0
    let activeMonths = []
    monthDistribution.forEach((count, month) => {
      if (count > maxCount) {
        maxCount = count
        activeMonths = [month]
      } else if (count === maxCount && maxCount > 0) {
        activeMonths.push(month)
      }
    })

    if (maxCount === 0) {
      return '今年暂无规律'
    }

    // 找出记录天数最多的月份
    let maxDays = 0
    let mostDaysMonths = []
    monthDays.forEach((days, month) => {
      if (days > maxDays) {
        maxDays = days
        mostDaysMonths = [month]
      } else if (days === maxDays && maxDays > 0) {
        mostDaysMonths.push(month)
      }
    })

    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    const activeMonthStrings = activeMonths.map(month => months[month])
    const mostDaysMonthStrings = mostDaysMonths.map(month => months[month])
    
    return `总记录：${totalDays}天 | 最活跃：${activeMonthStrings.join('、')} | 天数最多：${mostDaysMonthStrings.join('、')}`
  },

  // 分享报告
  async shareReport() {
    try {
      // 将canvas转换为图片
      const query = wx.createSelectorQuery()
      const canvas = query.select('#reportCanvas')
      const tempFilePath = await wx.canvasToTempFilePath({
        canvas: canvas.node
      })

      // 调用分享
      wx.shareFileMessage({
        filePath: tempFilePath.tempFilePath,
        success: () => {
          this.selectComponent('#customToast').showToast('分享成功')
          this.hideReportPreview()
        },
        fail: (error) => {
          // 静默处理分享失败
          this.selectComponent('#customToast').showToast('分享失败')
        },
        imageUrl: 'https://gitee.com/teajoy/image/raw/master/images/share-cover.png'
      })
    } catch (error) {
      // 静默处理分享报告失败
      this.selectComponent('#customToast').showToast('分享失败')
    }
  },

  // 保存报告到相册
  async saveReport() {
    try {
      // 将canvas转换为图片
      const query = wx.createSelectorQuery()
      const canvas = query.select('#reportCanvas')
      const tempFilePath = await wx.canvasToTempFilePath({
        canvas: canvas.node
      })

      // 保存到相册
      await wx.saveImageToPhotosAlbum({
        filePath: tempFilePath.tempFilePath
      })

      this.selectComponent('#customToast').showToast('保存成功')
      this.hideReportPreview()
    } catch (error) {
      // 静默处理保存报告失败
      this.selectComponent('#customToast').showToast('保存失败')
    }
  },

  // 隐藏报告预览
  hideReportPreview() {
    this.setData({
      showReportPreview: false
    })
  },

  // 检查记录数据
  checkRecords() {
    const records = this.getFilteredRecords();
    const normalRecords = records.filter(r => r.typeId === '1' || r.typeId === 1);

    const abnormalRecords = records.filter(r => r.typeId !== '1' && r.typeId !== 1);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '健康数据统计，关注身体健康！',
      path: '/pages/stats/stats',
      imageUrl: 'https://gitee.com/teajoy/image/raw/master/images/share-cover.png'
    }
  },
})